import { along, length, lineString } from '@turf/turf';
import type { LineFeature } from './shape';

// 计算两个向量之间的角度
export function calculateAngleBetweenVectors(
  v1: number[],
  v2: number[],
): number {
  const dot = v1[0] * v2[0] + v1[1] * v2[1];
  const mag1 = Math.sqrt(v1[0] ** 2 + v1[1] ** 2);
  const mag2 = Math.sqrt(v2[0] ** 2 + v2[1] ** 2);
  // 使用反余弦计算角度(弧度)并转换为度
  return Math.acos(dot / (mag1 * mag2)) * (180 / Math.PI);
}
// 计算三个点之间的角度
export function calculateAngleBetween3Points(
  prev: number[],
  curr: number[],
  next: number[],
): number {
  // 计算向量BA和BC
  const ba = [prev[0] - curr[0], prev[1] - curr[1]];
  const bc = [next[0] - curr[0], next[1] - curr[1]];
  // 使用反余弦计算角度(弧度)并转换为度
  return calculateAngleBetweenVectors(ba, bc);
}

export const getCenterOfLine = (coords: LineFeature) => {
  const line = lineString(coords.geometry.coordinates);
  const center = along(line, length(line) / 2).geometry.coordinates;
  return center;
};
